package com.mop.core.es.dao.config;

import com.google.gson.GsonBuilder;
import com.lemon.core.common.lang.util.PropertiesUtils;
import com.lemon.core.common.lang.util.StringUtils;
import com.lemon.core.common.lang.util.SystemEnvUtils;
import com.mop.core.es.dao.constant.ESConfig;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lemon
 * @ClassName JestConfig
 * @desc jest配置实例化
 * @Date 2018/12/2 13:54
 * @Version 1.0
 **/
public class JestConfig {

    private static String ES_HTTP_FREFIX = "http://";

    private static Integer ES_HTTP_PORT = 9200;

    private static String ES_SERVER_URIS;

    private static List<String> serverUris = new LinkedList<String>();

    public static List<String> getDefaultServerUris() {
        initDefaultConnectionParams();
        return serverUris;
    }

    public static JestClient getDefaultJestClient() {
        initDefaultConnectionParams();
        return getJestClient(serverUris);
    }

    public static JestClient getJestClient(List<String> serverUris) {
        serverUris = serverUris.stream().map(uri -> ES_HTTP_FREFIX + uri).collect(Collectors.toList());

        JestClientFactory factory = new JestClientFactory();
        HttpClientConfig httpClientConfig = new HttpClientConfig
                .Builder(serverUris)
                .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create())
                .multiThreaded(true)
                .readTimeout(10000)
                .build();
        factory.setHttpClientConfig(httpClientConfig);
        return factory.getObject();
    }

    private static void initDefaultConnectionParams() {
        PropertiesUtils propertiesUtils = PropertiesUtils.getInstance(ESConfig.DEFAULT_CONFIG_PATH);
        ES_SERVER_URIS = propertiesUtils.getString(ESConfig.CONFIG_PREFIX);
        if (StringUtils.isBlank(ES_SERVER_URIS)) {
            if (SystemEnvUtils.IS_PROD) {
                ES_SERVER_URIS = "mop.analysis.master, mop.analysis.node01, mop.analysis.node02";
            } else {
                ES_SERVER_URIS = "mop.test.analysis.master, mop.test.analysis.node01, mop.test.analysis.node02";
            }
        }

        for (String uri : ES_SERVER_URIS.split(",")) {
            String httpUri = uri.replaceAll(" ", "");
            if (!uri.contains(String.valueOf(ES_HTTP_PORT))) {
                httpUri += ":" + ES_HTTP_PORT;
            }
            serverUris.add(httpUri);
        }
    }

    private JestConfig() {

    }
}
